package com.chap02.datashow.service;


import com.chap02.datashow.dao.AppCategoryDao;
import com.chap02.datashow.entity.AppCategory;
import com.chap02.datashow.vo.TreeVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {

    @Resource
    AppCategoryDao appCategoryDao;


    public TreeVo getTree(){
        TreeVo tree = new TreeVo();

        List<TreeVo> vos = new ArrayList<>();

        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : list) {
            TreeVo treeVo = new TreeVo();
            BeanUtils.copyProperties(appCategory,treeVo);
            vos.add(treeVo);
        }
        for (TreeVo vo : vos) {
            if (vo.getParentid()==null){
                tree = findChildren(vo,vos);
            }
        }
        return tree;
    }

    private TreeVo findChildren(TreeVo vo, List<TreeVo> vos) {
        vo.setChildren(new ArrayList<>());

        for (TreeVo treeVo : vos) {
            if (vo.getId().equals(treeVo.getParentid())){
                vo.getChildren().add(treeVo);
                findChildren(treeVo,vos);
            }
        }
        return vo;
    }
}
